package com.cola.utils;

import com.cola.bean.User;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Grup:com.cola.utils
 * @Auther:cola
 * @Data:2021/4/16-2021-04-18:45
 * @version:1.0
 */
public class UserIO {
    private static List<User> users=new ArrayList<>();
    private static final String USER_FILE="ClothesSupermarketSystem19/src/main/resources/user.obj";

    //写入用户列表
    public boolean writeUser()throws BussinessException{
        try {
            ObjectOutputStream out =new ObjectOutputStream(new FileOutputStream(USER_FILE));
            out.writeObject(users);
            out.close();
            return true;
        } catch (IOException e) {
            throw new  BussinessException("io.write.error");
        }
    }
    //du用户列表
    public boolean readUser()throws BussinessException{
        try {
            ObjectInputStream in =new ObjectInputStream(new FileInputStream(USER_FILE));
            users =(List<User>) in.readObject();
            in.close();
            return true;
        } catch (IOException|ClassNotFoundException e) {
            throw new  BussinessException("io.read.error");
        }
    }
    //添加用户
    public void add(User user){
        user.setId(users.size()+1);
        users.add(user);
    }

    //查找用户
    public User findByUsernameAndpassword(String username,String password){
        UserIO userIO = new UserIO();
        userIO.readUser();
        for (User u:users){
            if (u.getUsername().equals(username)&&u.getPassword().equals(password)){
                return  u;
            }
        }
        return null;
    }
}
